package com.macrosolution.exdebito

import grails.converters.JSON;
import grails.plugin.springsecurity.annotation.Secured;
import grails.transaction.Transactional;

import java.text.SimpleDateFormat
import java.util.Date;

/**
 * ajaxflow Controller
 *
 * @author	Jeroen Wesbeek <work@osx.eu>
 * @package AjaxFlow
 */
@Secured(['ROLE_ADMIN','ROLE_AMM','ROLE_BCKOFF','ROLE_AVV','ROLE_CC','ROLE_C','ROLE_SC'])
class InterviewController {
	// the pluginManager is used to check if the Grom
	// plugin is available so we can 'Grom' development
	// notifications to the unified notifications daemon
	// (see http://www.grails.org/plugin/grom)
	public static final long MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
	public static final long MILLIS_PER_YEAR = 365 * MILLIS_PER_DAY;
	def pluginManager
	def springSecurityService
	def jasperService
	
	def list = {
		User secUser =springSecurityService.currentUser
		List<User> families=(List<User>)secUser.getFamily()

		//BISOGNA METTERE SUL DB IL FATTO CHE User in Interview deve essere un indice
		Set<Interview> inter = Interview.findAllByUserInList(families,[sort: "lastUpdated", order: "desc"]);
		ArrayList interviews = new ArrayList() 
		for(Interview i:inter){
			if(i?.customer){
				interviews.add(i)
			} else{
				i.delete(flush:true)
			}
		}
		render view:'list', model:[interviews:interviews,secUser:secUser]	
	}
	
	def edit={
		redirect action:'pages',id:params.id
	}
	
	def delete={Interview interview->
		String message
		if(interview){
			User secUser =springSecurityService.currentUser
			if(interview.isEditableByUser(secUser)){
				List<String> auths =secUser.authorities*.authority
				if(auths.contains("ROLE_ADMIN") ||auths.contains("ROLE_AMM")){
					List anomalie = new ArrayList()
					anomalie = AnomaliaBancaria.findAllByInterviewId(interview.id)
					for(a in anomalie) {
						Pratica p = Pratica.findByAnomaliaBancaria(a)
						AnomaliaCounter ac = AnomaliaCounter.findByInterIDAndAnomalID(interview.id,a.getAnomaliaBancariaType().id)
						ac.counter--
						ac.save(flush:true)
						p.delete(flush:true)
					}
					interview.delete(flush:true)
				}else{
					User amm = secUser.getParentRole("ROLE_AMM");
					if(amm){
						List anomalie = new ArrayList()
						anomalie = AnomaliaBancaria.findAllByInterviewId(interview.id)
						for(a in anomalie) {
							Pratica p = Pratica.findByAnomaliaBancaria(a)
							p.user=amm
							p.save(flush:true)
						}
						interview.user=amm
						interview.save(flush:true)
					}
				}
					message="{'message':'Intervista cancellata con successo!'}"
			}else{
					message="{'message':'Non si possiedono i permessi per cancellare l intervista selezionata!'}"
			}			
		}else{
			message="{'message':'impossibile trovare l intervista selezionata'}"			
		}
		render JSON.parse(message) as JSON
	}
	
	def search={
			User secUser =springSecurityService.currentUser		
		render view:'search', model:[secUser:secUser]	
	}
	/**
	 * index method, redirect to the webflow
	 * @void
	 */
	def index = {
		// Grom a development message
		if (pluginManager.getGrailsPlugin('grom')) "redirecting into the webflow".grom()
		/**
		 * Do you believe it in your head?
		 * I can go with the flow
		 * Don't say it doesn't matter (with the flow) matter anymore
		 * I can go with the flow (I can go)
		 * Do you believe it in your head?
		 */		
		redirect(action: 'pages')
	}

	
	/**
	 * WebFlow definition
	 * @void
	 */
	def pagesFlow = {
		// start the flow
		onStart {
			// Grom a development message
			if (pluginManager.getGrailsPlugin('grom')) "entering the WebFlow".grom()

			// define variables in the flow scope which is availabe
			// throughout the complete webflow also have a look at
			// the Flow Scopes section on http://www.grails.org/WebFlow
			//
			// The following flow scope variables are used to generate
			// wizard tabs. Also see common/_tabs.gsp for more information
			
			flow.page = 0
			flow.pages = [
				[title: 'Cliente'],
				[title: 'Lavoro'],
				[title: 'Famiglia'],
				[title: 'Beni e Propriet&agrave;'],
				[title: 'Debito'],
//				[title: 'Pre Sovrad.'],
//				[title: 'Post Sovrad.'],
				[title: 'Documenti'],
				[title: 'Scheda Riepilogativa']
			]
			flow.cancel = true;
			flow.quickSave = true;
			
			success()
		}

		// render the main wizard page which immediately
		// triggers the 'next' action (hence, the main
		// page dynamically renders the study template
		// and makes the flow jump to the study logic)
		mainPage {
			
			render(view: "/interview/index")
			onRender {
				// Grom a development message
				if (pluginManager.getGrailsPlugin('grom')) "rendering the main Ajaxflow page (index.gsp)".grom()
				// let the view know we're in page 1
				flow.page = 1
				success()
			}
			on("next").to "cliente"
		}
		// first wizard page
		cliente {
			render(view: "_cliente")
			onStart{
				// GESTIONE EDIT INTERVISTA NEL FLUSSO
				if(params.id){
					flow.interview = Interview.get(params.id)
					
					flow.customer=flow.interview.customer
					[interview:flow.interview,customer:flow.customer]
				}
				if(!flow.interview){
					Interview interview =new Interview() 
					def current_user = springSecurityService.currentUser
					interview.user = current_user 
					interview.save(flush:true)		
					flow.interview = interview
					[interview:flow.interview]
				}
			}
        
			onRender {
				// Grom a development message
				if (pluginManager.getGrailsPlugin('grom')) ".rendering the partial: pages/_page_one.gsp".grom()
					flow.page = 1
					success()					
			}
			
			on("error").to "error"
			on("next") {
				outCliente(flow);	
			}.to "lavoro"
			on("toPageOne") {
				outCliente(flow);
			}.to "cliente"
			on("toPageTwo") {
				outCliente(flow);
			}.to "lavoro"
			on("toPageThree") {
				outCliente(flow);
			}.to "famiglia"
			on("toPageFour") {
				outCliente(flow);
			}.to "beni_propieta"
			on("toPageFive") {
				outCliente(flow);
			}.to "debito"
			on("toPageSix") {
				outCliente(flow);
			}.to "interview_doc"
			on("toPageSeven") {
				outCliente(flow);
				flow.page = 7
			}.to "scheda_riepilogativa"
		}

		// second wizard page
		lavoro {
			render(view: "_lavoro")
			onStart{			
				[customer:flow.customer,interview:flow.interview]
			}
			
			onRender {
				// Grom a development message
				if (pluginManager.getGrailsPlugin('grom')) ".rendering the partial: pages/_page_two.gsp".grom()				
				flow.page = 2
				success()
			}
			on("next"){
				outLavoro(flow);
			}.to "famiglia"
			on("previous"){
				outLavoro(flow);
			}.to "cliente"
			on("toPageOne"){
				outLavoro(flow);
			}.to "cliente"
			on("toPageTwo"){
				outLavoro(flow);
			}.to "lavoro"
			on("toPageThree"){
				outLavoro(flow);
			}.to "famiglia"
			on("toPageFour"){
				outLavoro(flow);
			}.to "beni_propieta"
			on("toPageFive"){
				outLavoro(flow);
			}.to "debito"
			on("toPageSix") {
				outCliente(flow);
			}.to "interview_doc"
			on("toPageSeven") {
				outLavoro(flow);
				flow.page = 7
			}.to "scheda_riepilogativa"
		}


		// third wizard page
		famiglia {
			render(view: "_famiglia")
			onStart{
				[customer:flow.customer,interview:flow.interview]
			}
			onRender {
				// Grom a development message
				if (pluginManager.getGrailsPlugin('grom')) ".rendering the partial pages/_page_three.gsp".grom()
				flow.page = 3
				success()
			}
			on("next"){
				outFamiglia(flow);
			}.to "beni_propieta"
			on("previous"){
				outFamiglia(flow);
			}.to "lavoro"
			on("toPageOne"){
				outFamiglia(flow);
			}.to "cliente"
			on("toPageTwo"){
				outFamiglia(flow);
			}.to "lavoro"
			on("toPageThree"){
				outFamiglia(flow);
			}.to "famiglia"
			on("toPageFour"){
				outFamiglia(flow);
			}.to "beni_propieta"
			on("toPageFive"){
				outFamiglia(flow);
			}.to "debito"
			on("toPageSix") {
				outCliente(flow);
			}.to "interview_doc"
			on("toPageSeven") {
				outFamiglia(flow);
				flow.page = 7
			}.to "scheda_riepilogativa"
		}
		

		// forth wizard page
		beni_propieta {
			render(view: "_beni_propieta")
			onStart{
				[customer:flow.customer,interview:flow.interview]
			}
			onRender {
				// Grom a development message
				if (pluginManager.getGrailsPlugin('grom')) ".rendering the partial pages/_page_four.gsp".grom()
				flow.page = 4
				success()
			}
			on("next"){
				outBeniPropieta(flow);
			}.to "debito"
			on("previous"){
				outBeniPropieta(flow);
			}.to "famiglia"
			on("toPageOne"){
				outBeniPropieta(flow);
			}.to "cliente"
			on("toPageTwo"){
				outBeniPropieta(flow);
			}.to "lavoro"
			on("toPageThree"){
				outBeniPropieta(flow);
			}.to "famiglia"
			on("toPageFour"){
				outBeniPropieta(flow);
			}.to "beni_propieta"
			on("toPageFive"){
				outBeniPropieta(flow);
			}.to "debito"
			on("toPageSix") {
				outBeniPropieta(flow);
			}.to "interview_doc"
			on("toPageSeven") {
				outBeniPropieta(flow);
				flow.page = 7
			}.to "scheda_riepilogativa"
		}

		// five wizard page
		debito {
			render(view: "_debito")
			onStart{
				[customer:flow.customer,interview:flow.interview]
			}
			onRender {
				// Grom a development message
				if (pluginManager.getGrailsPlugin('grom')) ".rendering the partial pages/_page_five.gsp".grom()				
				flow.page = 5
				success()
			}
			on("next"){
				outDebito(flow);
			}.to "interview_doc"
			on("previous"){
				outDebito(flow);
			}.to "beni_propieta"
			on("toPageOne"){
				outDebito(flow);
			}.to "cliente"
			on("toPageTwo"){
				outDebito(flow);
			}.to "lavoro"
			on("toPageThree"){
				outDebito(flow);
			}.to "famiglia"
			on("toPageFour"){
				outDebito(flow);
			}.to "beni_propieta"
			on("toPageFive"){
				outDebito(flow);
			}.to "debito"
			on("toPageSix") {
				outDebito(flow);
			}.to "interview_doc"
			on("toPageSeven") {
				outDebito(flow);
				flow.page = 7
			}.to "scheda_riepilogativa"
		}

		// sixt page
		interview_doc {
			render(view: "_interview_doc")
			onStart{
				[customer:flow.customer,interview:flow.interview]
			}
			onRender {
				// Grom a development message
				if (pluginManager.getGrailsPlugin('grom')) ".rendering the partial pages/_final_page.gsp".grom()
				
				flow.page = 6
				success()
			}
			on("next"){
				outInterviewDoc(flow);
			}.to "scheda_riepilogativa"
			on("previous"){
				outInterviewDoc(flow);
			}.to "debito"
			on("toPageOne"){
				outInterviewDoc(flow);
			}.to "cliente"
			on("toPageTwo"){
				outInterviewDoc(flow);
			}.to "lavoro"
			on("toPageThree"){
				outInterviewDoc(flow);
			}.to "famiglia"
			on("toPageFour"){
				outInterviewDoc(flow);
			}.to "beni_propieta"
			on("toPageFive") {
				outInterviewDoc(flow);
			}.to "debito"
			on("toPageSix") {
				outInterviewDoc(flow);
			}.to "interview_doc"
			on("toPageSeven") {
				outInterviewDoc(flow);
				flow.page = 7
			}.to "scheda_riepilogativa"
		}
	
		
		// last wizard page
		scheda_riepilogativa {
			render(view: "_scheda_riepilogativa")
			onStart{
				[customer:flow.customer,interview:flow.interview]
			}
			onRender {
				// Grom a development message
				if (pluginManager.getGrailsPlugin('grom')) ".rendering the partial pages/_final_page.gsp".grom()
				
				flow.page = 7
				success()
			}

			on("previous"){
				outSR(flow);
			}.to "interview_doc"
			on("toPageOne"){
				outSR(flow);
			}.to "cliente"
			on("toPageTwo"){
				outSR(flow);
			}.to "lavoro"
			on("toPageThree"){
				outSR(flow);
			}.to "famiglia"
			on("toPageFour"){
				outSR(flow);
			}.to "beni_propieta"
			on("toPageFive") {
				outSR(flow);
			}.to "debito"
			on("toPageSix") {
				outSR(flow);
			}.to "interview_doc"
			on("toPageSeven") {
			}.to "scheda_riepilogativa"
		}
		
		// save action
		save {
			action {
				// here you can validate and save the
				// instances you have created in the
				// ajax flow.
				try {
					// Grom a development message
					if (pluginManager.getGrailsPlugin('grom')) ".persisting instances to the database...".grom()

					// put your bussiness logic in here
					success()
				} catch (Exception e) {
					// put your error handling logic in
					// here
					flow.page = 7
					error()
				}
			}
			on("error").to "error"
			on(Exception).to "error"
			on("success").to "finalPage"
		}

		// render errors
		error {
			render(view: "_error")
			onRender {
				// Grom a development message
				if (pluginManager.getGrailsPlugin('grom')) ".rendering the partial pages/_error.gsp".grom()

				// set page to 4 so that the navigation
				// works (it is disabled on the final page)
				flow.page = 7
			}
			on("next").to "save"
			on("previous").to "save"
			on("toPageOne").to "save"
			on("toPageTwo").to "save"
			on("toPageThree").to "save"
			on("toPageFour").to "save"
			on("toPageFive").to "save"
			on("toPageSix").to "save"
			on("toPageSeve").to "save"
		}
	}
	
	private outCliente(flow){
		def current_user = springSecurityService.currentUser
		Interview interview = Interview.findById(flow.interview.id)?:new Interview()
		Customer customer;
		if(flow.customer){
			customer= flow.customer
		}else{
			customer=new Customer()
		}
		if(!current_user.isReadOnly()){
		if(params.born){
			customer.born=new SimpleDateFormat("dd/MM/yyyy").parse(params.born)
			customer.age=params.getInt('age')
			params.remove('born')
			params.remove('age')
		}
		if(params.getLong('born_province')){
			customer.bornProvince=Provincia.get(params.getLong('born_province'))
			params.remove('born_province')
		}
		if(params.getLong('born_municipality')){
			customer.bornMunicipality =Comune.get(params.getLong('born_municipality'))
			params.remove('born_municipality')
		}
		if(params.getLong('residence_province')){		
			Address residence = customer.residence?:new Address()
			residence.province=Provincia.get(params.getLong('residence_province'))
			residence.municipality=Comune.get(params.getLong('residence_municipality'))
			residence.cap=params.residence_cap
			residence.address=params.residence_address
			residence.save(flush:true)
			customer.residence=residence
		}
		if(params.abode_province){
			if(customer.abode){
				Address a = Address.findById(customer.abode.id)
				a.delete()
				customer.abode=null
				customer.save(flush:true)
			}
			Address abode = new Address()
			abode.province=Provincia.get(params.getLong('abode_province'))
			abode.municipality=Comune.get(params.getLong('abode_municipality'))
			abode.cap=params.abode_cap
			abode.address=params.abode_address
			abode.save(flush:true)
			customer.abode=abode
		}
		customer.properties=params
		customer.save(flush:true)
		
		if(customer.personaGiuridica){
			PersonaGiuridica pg = PersonaGiuridica.findById(customer.personaGiuridica.id)
			if(pg.pgResidence){
				Address pgr = Address.findById(pg.pgResidence.id)
				pgr.delete()
			}
			pg.delete()
			customer.personaGiuridica=null
		}
		if(params.pgName || params.pgCf || params.pgPiva){
			PersonaGiuridica pg = new PersonaGiuridica()
			pg.pgName = params.pgName?:("")
			pg.pgCf = params.pgCf?:("")
			pg.pgPiva = params.pgPiva?:("")
			pg.pgEmail = params.pgEmail?:("")
			pg.pgPhone = params.pgPhone?:("")
			pg.pgMobile = params.pgMobile?:("")
			if(params.pgResidence_province){
				Address pgResidence = new Address()
				pgResidence.province=Provincia.get(params.getLong('pgResidence_province'))
				pgResidence.municipality=Comune.get(params.getLong('pgResidence_municipality'))
				pgResidence.cap=params.pgResidence_cap
				pgResidence.address=params.pgResidence_address
				pgResidence.save(flush:true)
				pg.pgResidence=pgResidence	
			}
			pg.save(flush:true)
			customer.personaGiuridica=pg			
		}
		customer.save(flush:true)
		
		interview.customer = customer
		interview.save(flush:true)
		}
		flow.customer=customer
		flow.interview = interview
		[customer:flow.customer,interview:flow.interview]
	}
	
	private outLavoro(flow){
		def current_user = springSecurityService.currentUser
		Customer customer= flow.customer?: new Customer()

		if(!current_user.isReadOnly()){
			if(customer?.job){
				Job j = Job.findById(customer.job.id)
				j.delete()
				customer.job=null
				customer.save(flush:true)
			}
		if(params.value){
			Long idJobType=params.getLong('value')
			JobType jt=JobType.get(idJobType)
			if( idJobType< 4 && idJobType > -1){
				DipPensCassIntJob dpcInt = new DipPensCassIntJob()
				if(params.redditoNettoAnnuo){
					String reddito=currencyFormatter(params.redditoNettoAnnuo)
					
					BigDecimal sRed = new BigDecimal(reddito);
					dpcInt.redditoNettoAnnuo=sRed
				}
				dpcInt.mensilita=params.getInt('mensilita')?:(0)
				dpcInt.contractType=params.contractType?:("")
				dpcInt.impiegoType=params.impiegoType?:("")
				dpcInt.jobType=jt
				dpcInt.save(flush:true)
				customer.job=dpcInt				
			} else if(params.getInt('value') == 4){
				Disoccuped disoc = new Disoccuped()
				disoc.disoc=true
				disoc.jobType=jt
				disoc.save(flush:true)
				customer.job=disoc				
			} else if(params.getInt('value') > 4){
				ImprArtProfAgric iapAgr = new ImprArtProfAgric()
				iapAgr.jobType =jt				
				if(params.attivoLastYear){
					String f = currencyFormatter(params.attivoLastYear);
					BigDecimal fat = new BigDecimal(f);
					iapAgr.attivoLastYear=fat
				}
				if(params.ricaviLordiLastYear){
					String f = params.ricaviLordiLastYear;
					BigDecimal fat = new BigDecimal(currencyFormatter(f));
					iapAgr.ricaviLordiLastYear=fat
				}
				if(params.debitiLastYear){
					String f = params.debitiLastYear;
					BigDecimal fat = new BigDecimal(currencyFormatter(f));
					iapAgr.debitiLastYear=fat
				}
				if(params.attivoSecondLastYear){
					String f = params.attivoSecondLastYear;
					BigDecimal fat = new BigDecimal(currencyFormatter(f));
					iapAgr.attivoSecondLastYear=fat
				}
				if(params.ricaviLordiSecondLastYear){
					String f = params.ricaviLordiSecondLastYear;
					BigDecimal fat = new BigDecimal(currencyFormatter(f));
					iapAgr.ricaviLordiSecondLastYear=fat
				}
				if(params.debitiSecondLastYear){
					String f = params.debitiSecondLastYear;
					BigDecimal fat = new BigDecimal(currencyFormatter(f));
					iapAgr.debitiSecondLastYear=fat
				}
				if(params.attivoThirdLastYear){
					String f = params.attivoThirdLastYear;
					BigDecimal fat = new BigDecimal(currencyFormatter(f));
					iapAgr.attivoThirdLastYear=fat
				}
				if(params.ricaviLordiThirdLastYear){
					String f = params.ricaviLordiThirdLastYear;
					BigDecimal fat = new BigDecimal(currencyFormatter(f));
					iapAgr.ricaviLordiThirdLastYear=fat
				}
				if(params.debitiThirdLastYear){
					String f = params.debitiThirdLastYear;
					BigDecimal fat = new BigDecimal(currencyFormatter(f));
					iapAgr.debitiThirdLastYear=fat
				}
				iapAgr.activityType=params.activityType?:("")
				iapAgr.save(flush:true)
				customer.job=iapAgr
			}
		}	
			
		if(customer.renditaTitDep){
			customer.renditaTitDep.clear()
		}		
		if(params.rendita || params.rendita_importo){
			
			List renditaTipDepList = new ArrayList()		
			for(int i=0 ; i < params.list('rendita').size() ; i++){
				RenditaTitDep rtd = new RenditaTitDep();
				if(params.list('rendita')[i] && !(params.list('rendita')[i]=='')){
					rtd.setTipologyRendita(params.list('rendita')[i])
				} else {
					rtd.setTipologyRendita('')
				}
				if(params.list('rendita_importo')[i] && !(params.list('rendita_importo')[i]=='')){
					String f =  params.list('rendita_importo')[i]
					
					BigDecimal fat = new BigDecimal(currencyFormatter(f))
					rtd.setTotEuroRendita(fat)
				} else {
					BigDecimal z = new BigDecimal(0)
					rtd.setTotEuroRendita(z)
				}
				renditaTipDepList.add(rtd)
				rtd.save(flush:true)				
			}
			customer.renditaTitDep=renditaTipDepList
			flow.customer.renditaTitDep=renditaTipDepList
			}
		customer.save(flush:true);
		}		
	}
	
	private outFamiglia(flow){
		def current_user = springSecurityService.currentUser
		Customer customer = Customer.get(flow.customer.id)
		if(!current_user.isReadOnly()){
		if(params.familiesNumber){
			customer.familiesNumber=params.getInt('familiesNumber')
		}
		if(customer.families){
			customer.families.clear()
		}
		if(params.familyType || params.job || params.ran){
			List <Family> family = new ArrayList();

			for(int i=0 ; i < params.list('job').size() ; i++){
				Family fam = new Family()
				if(params.list('familyType')[i] && !(params.list('familyType')[i]=='')){
					fam.type = FamilyType.findByValue(params.list('familyType')[i])
				} else {
					fam.type = FamilyType.findByValue('Altro')
				}						
				if(params.list('job')[i] && !(params.list('job')[i]=='')){
					fam.setJob(params.list('job')[i])
				} else {
					fam.setJob('')
				}
				if(params.list('ran')[i] && !(params.list('ran')[i]=='')){
					String f =  params.list('ran')[i]
					BigDecimal fat = new BigDecimal(currencyFormatter(f))
					fam.setRan(fat)
				} else {
					BigDecimal z = new BigDecimal(0)
					fam.setRan(z)
				}
				family.add(fam)
				fam.save(flush:true)
			}			
			customer.families=family
			flow.customer.families=family
			}
		customer.save(flush:true)
		}
	}

	
	private outBeniPropieta(flow){
		def current_user = springSecurityService.currentUser
		if(!current_user.isReadOnly()){
		Customer customer = Customer.get(flow.customer.id)
		if(customer.immobile){
			customer.immobile.clear()
		}
		if(params.immobileType || params.metriQuadri || params.immobil_province 
			|| params.rataMensileMutuo || params.valoreMutuo || params.stimaMercatoAttuale){

			List <Immobile> immobileList = new ArrayList();			
			for(int i=0 ; i < params.list('immobileType').size() ; i++){
				Immobile imm = new Immobile();
				if(params.list('immobileType')[i] && !(params.list('immobileType')[i]=='')){
					imm.immobileType = ImmobileType.findByImmobileType(params.list('immobileType')[i])
				} else {
					imm.immobileType = ImmobileType.findByImmobileType('ALTRO')
				}
				if(params.list('metriQuadri')[i] && !(params.list('metriQuadri')[i]=='')){
					String f =  params.list('metriQuadri')[i]
					BigDecimal fat = new BigDecimal(f)
					imm.setMetriQuadri(fat)
				} else {
					BigDecimal z = new BigDecimal(0)
					imm.setMetriQuadri(z)
				}
				if(params.list('immobil_province')[i] && !(params.list('immobil_province')[i]=='')){
					imm.setProvince(Provincia.get(new Long(params.list('immobil_province')[i])))
				} 
				if(params.list('immobil_municipality')[i] && !(params.list('immobil_municipality')[i]=='')){
					imm.setMunicipality(Comune.get(new Long(params.list('immobil_municipality')[i])))
				} 
				if(params.list('immobil_cap')[i] && !(params.list('immobil_cap')[i]=='')){
					imm.setCap(params.list('immobil_cap')[i])
				} else {
					imm.setCap('0')
				}
				if(params.list('immobil_address')[i] && !(params.list('immobil_address')[i]=='')){
					imm.setAddress(params.list('immobil_address')[i])
				} else {
					imm.setAddress('')
				}
				if(params.list('rataMensileMutuo')[i] && !(params.list('rataMensileMutuo')[i]=='')){
					String f =  params.list('rataMensileMutuo')[i]
					BigDecimal fat = new BigDecimal(currencyFormatter(f))
					imm.setRataMensileMutuo(fat)
				} else {
					BigDecimal z = new BigDecimal(0)
					imm.setRataMensileMutuo(z)
				}
				
				if(params.list('valoreMutuo')[i] && !(params.list('valoreMutuo')[i]=='')){
					String f =  params.list('valoreMutuo')[i]
					BigDecimal fat = new BigDecimal(currencyFormatter(f))
					imm.setValoreMutuo(fat)
				} else {
					BigDecimal z = new BigDecimal(0)
					imm.setValoreMutuo(z)
				}
				
				if(params.list('stimaMercatoAttuale')[i] && !(params.list('stimaMercatoAttuale')[i]=='')){
					String f =  params.list('stimaMercatoAttuale')[i]
					BigDecimal fat = new BigDecimal(currencyFormatter(f))
					imm.setStimaMercatoAttuale(fat)
				} else {
					BigDecimal z = new BigDecimal(0)
					imm.setStimaMercatoAttuale(z)
				}
				immobileList.add(imm)
				imm.save(flush:true)
			}
			customer.immobile=immobileList
			flow.customer.immobile=immobileList
		} 
			
		if(customer.altroBene){
			customer.altroBene.clear()
		}
		if(params.tipologyBene || params.valoreStimaMerc || params.note){
			
			List <AltroBeneProp> altroBeneList = new ArrayList();			
			for(int i=0 ; i < params.list('tipologyBene').size() ; i++){
				AltroBeneProp abp = new AltroBeneProp();
				if(params.list('tipologyBene')[i] && !(params.list('tipologyBene')[i]=='')){
					abp.setTipologyBene(params.list('tipologyBene')[i])
				} else {
					abp.setTipologyBene('')
				}
				if(params.list('valoreStimaMerc')[i] && !(params.list('valoreStimaMerc')[i]=='')){
					String f =  params.list('valoreStimaMerc')[i]
					BigDecimal fat = new BigDecimal(currencyFormatter(f))
					abp.setValoreStimaMerc(fat)
				} else {
					BigDecimal z = new BigDecimal(0)
					abp.setValoreStimaMerc(z)
				}
				if(params.list('note')[i] && !(params.list('note')[i]=='')){
					abp.setNote(params.list('note')[i])
				} else {
					abp.setNote('')
				}
				altroBeneList.add(abp)
				abp.save(flush:true)
			}
			customer.altroBene=altroBeneList
			flow.customer.altroBene=altroBeneList
			}			
		customer.save(flush:true)
		}	
	}
	
	private outDebito(flow){
		def current_user = springSecurityService.currentUser
		if(!current_user.isReadOnly()){
		Interview interview = Interview.findById(flow.interview.id)?:new Interview()
				if(interview.acdCPI){
					ApprofCessDelCPI a = interview.acdCPI
					a.delete()
					interview.acdCPI=null
				}
			if(params.cessioniDeleghe ||params.cPI){
				ApprofCessDelCPI a = new ApprofCessDelCPI();
				if(params.cessioniDeleghe){				
					a.cessioniDeleghe=(Boolean.parseBoolean(params.cessioniDeleghe))
				}
				if(params.cPI){		
					a.cPI=Boolean.parseBoolean(params.cPI)
				}
				a.save(flush:true)
				interview.acdCPI = a
			}				
			interview.note=params.note?:("")
						
			if(interview.motiveInterview){
				MotiveInterview m = interview.motiveInterview
				m.delete()
				interview.motiveInterview = null
			}
			
			if(!(params.motiveSelect.equals("no"))){			
				MotiveInterview m = new MotiveInterview()
				m.motiveInterviewType = MotiveInterviewType.findById(params.getInt('motiveSelect'))
				if(m.motiveInterviewType.id!=4 && params.altroSpec){params.altroSpec = ''}
				m.altroSpec = params.altroSpec?:("")
				m.save(flush:true)
				interview.motiveInterview = m				
			}		
			interview.save(flush:true);

			Customer customer = Customer.get(flow.customer.id)
			if(customer.debito){
				customer.debito.clear()
			}
		if(params.debitType || params.credit || params.capitalRes || params.rate || params.partner || params.notes){

			List <Debit> debitList = new ArrayList();		
			for(int i=0 ; i < params.list('debitType').size() ; i++){
				Debit deb = new Debit();
				
				if(params.list('debitType')[i] && !(params.list('debitType')[i]=='')){
					deb.type = DebitType.findByType(params.list('debitType')[i])
				} else {
					deb.type = FamilyType.findByType('Altro')
				}
				if(params.list('credit')[i] && !(params.list('credit')[i]=='')){
					deb.setCredit(params.list('credit')[i])
				} else {
					deb.setCredit('')
				}				
				if(params.list('capitalRes')[i] && !(params.list('capitalRes')[i]=='')){
					String f =  params.list('capitalRes')[i]
					BigDecimal fat = new BigDecimal(currencyFormatter(f))
					deb.setCapitalRes(fat)
				} else {
					BigDecimal z = new BigDecimal(0)
					deb.setCapitalRes(z)
				}
				if(params.list('rate')[i] && !(params.list('rate')[i]=='')){
					String f =  params.list('rate')[i]
					BigDecimal fat = new BigDecimal(currencyFormatter(f))
					deb.setRate(fat)
				} else {
					BigDecimal z = new BigDecimal(0)
					deb.setRate(z)
				}				
				if(params.list('partner')[i] && !(params.list('partner')[i]=='')){
					deb.setPartner(params.list('partner')[i])
				} else {
					deb.setPartner('')
				}
				if(params.list('notes')[i] && !(params.list('notes')[i]=='')){
					deb.setNotes(params.list('notes')[i])
				} else {
					deb.setNotes('')
				}				
				debitList.add(deb)
				deb.save(flush:true)
			}
			customer.debito=debitList
			flow.customer.debito=debitList
			}
		customer.save(flush:true)
		}
	}

	
	private outInterviewDoc(flow){
			
		flow.interview=Interview.findById(params.interviewId)
	}

			
	private outSR(flow){
	}
		
		
	def calculate_age(){
		if(params.born){
			Date now = new Date();
			Date born =new SimpleDateFormat('dd/MM/yyyy').parse(params.born)
			long ageMillis = System.currentTimeMillis() - born.getTime();
			Calendar nowC = new GregorianCalendar()
			nowC.setTimeInMillis(now.getTime())
			Calendar bornC = new GregorianCalendar()
			bornC.setTimeInMillis(born.getTime())
			int curYear = nowC.get(Calendar.YEAR);
			int curMonth = nowC.get(Calendar.MONTH);
			int curDay = nowC.get(Calendar.DAY_OF_MONTH);
			int year = bornC.get(Calendar.YEAR);
			int month = bornC.get(Calendar.MONTH);
			int day = bornC.get(Calendar.DAY_OF_MONTH);
			int age = curYear - year;
				if (curMonth < month || (month == curMonth && curDay < day)) {
				    age--;
				}
			render 	age	
		}else{
		render ''
		}		
	}
	
	def renderCassIntJob(){
		if(params.getInt('jobId') < 4 && params.getInt('jobId') > -1){
			render(template:'/interview/common/dipPensCassIntJob',	 
				model:[redditoNettoAnnuo:((params.redditoNettoAnnuo!='null')?params.redditoNettoAnnuo:''),mensilita:((params.mensilita!='null')?params.mensilita:''),
						contractType:((params.contractType!='null')?params.contractType:''),impiegoType:((params.impiegoType!='null')?params.impiegoType:'')])
		} else if(params.getInt('jobId') == 4 || params.getInt('jobId') == -1){
			render(template:'/interview/common/disoccupato')
		} else {
			render(template:'/interview/common/imprArtProfAgric',
				model:[attivoLastYear:((params.attivoLastYear!='null')?params.attivoLastYear:''),ricaviLordiLastYear:((params.ricaviLordiLastYear!='null')?params.ricaviLordiLastYear:''),
						debitiLastYear:((params.debitiLastYear!='null')?params.debitiLastYear:''),attivoSecondLastYear:((params.attivoSecondLastYear!='null')?params.attivoSecondLastYear:''),
						ricaviLordiSecondLastYear:((params.ricaviLordiSecondLastYear!='null')?params.ricaviLordiSecondLastYear:''),debitiSecondLastYear:((params.debitiSecondLastYear!='null')?params.debitiSecondLastYear:''),
						attivoThirdLastYear:((params.attivoThirdLastYear!='null')?params.attivoThirdLastYear:''),ricaviLordiThirdLastYear:((params.ricaviLordiThirdLastYear!='null')?params.ricaviLordiThirdLastYear:''),
						debitiThirdLastYear:((params.debitiThirdLastYear!='null')?params.debitiThirdLastYear:''),activityType:((params.activityType!='null')?params.activityType:'')])
		}
	}
	
	
	def renderAnomaliaBancaria(){
		render(template:'/interview/common/anomaliaBancaria')
	}
	
	
	def generateAnomaliaAndPratica(){
			if(params.anomalia && params.intId){

			//Creo Anomalia
			AnomaliaBancariaType abt = AnomaliaBancariaType.findByAnomaliaBancariaType(params.anomalia)
			AnomaliaBancaria ab = new AnomaliaBancaria()
			ab.anomaliaBancariaType = abt
			ab.setInterviewId(params.getInt('intId'))
			ab.refName = params.refName?:("")
			ab.save(flush:true)
			
			//Aumeto il contatore nella tabella AnomaliaType-Interview
			AnomaliaCounter  aCounter = new AnomaliaCounter();
			
			if(AnomaliaCounter.findByInterIDAndAnomalID(params.getInt('intId'), abt.id)){
				aCounter = AnomaliaCounter.findByInterIDAndAnomalID(params.getInt('intId'), abt.id)
				aCounter.counter++
			} else {
				aCounter.interID = ab.getInterviewId()
				aCounter.anomalID = abt.id
				aCounter.counter = 1
			}
			
			aCounter.save(flush:true)
			
			//Creo Pratica
			Pratica p = new Pratica()
			p.anomaliaBancaria = ab
			p.user = (Interview.findById(ab.interviewId)).getUser()
			p.save(flush:true)
			
				render p.identifier
			}

	}
	
	
	def renderAnomalieBancarieList(){
		
		String abExist = ""
		List abContoC = new ArrayList()
		List abMutuo = new ArrayList()
		List abLeasing = new ArrayList()
		List abDerivato = new ArrayList()
		
		User secUser =springSecurityService.currentUser
		List fam = secUser.getFamily()
		List anBancarie=AnomaliaBancaria.findAllByInterviewId(params.getInt('interviewId'))
		if(anBancarie){
			for(int i = 0; i < anBancarie.size(); i++){
				Pratica p  = Pratica.findByAnomaliaBancaria(anBancarie[i])
				if(fam && fam.contains(p.user)){
					if ((anBancarie[i].anomaliaBancariaType?.anomaliaBancariaType).equals("Conto Corrente")){
						List l = new ArrayList()
						l.add(p.identifier)
						l.add(anBancarie[i].getRefName())
						l.add(anBancarie[i].getDateCreated())
						abContoC.add(l)
					} else if ((anBancarie[i].anomaliaBancariaType?.anomaliaBancariaType).equals("Mutuo")){
						List l = new ArrayList()
						l.add(p.identifier)
						l.add(anBancarie[i].getRefName())
						l.add(anBancarie[i].getDateCreated())
						abMutuo.add(l)
					} else if ((anBancarie[i].anomaliaBancariaType?.anomaliaBancariaType).equals("Leasing")){
						List l = new ArrayList()
						l.add(p.identifier)
						l.add(anBancarie[i].getRefName())
						l.add(anBancarie[i].getDateCreated())
						abLeasing.add(l)
					} else {
						List l = new ArrayList()
						l.add(p.identifier)
						l.add(anBancarie[i].getRefName())
						l.add(anBancarie[i].getDateCreated())
						abDerivato.add(l)
					}

				}
			}
			if(!abDerivato.isEmpty() || !abLeasing.isEmpty() || !abMutuo.isEmpty() || !abContoC.isEmpty()){
				abExist = "true"
			}		
		}
	
		render(template:'/interview/common/anomalieBancarieList',model:[abExist:abExist, abContoC:abContoC, abMutuo:abMutuo, abLeasing:abLeasing, abDerivato:abDerivato])			
	}
	
	
	@Transactional
	def deleteABandPratica(){
		Pratica p = Pratica.findByIdentifier(params.codPratica)
			String message
			if(p){
				User secUser =springSecurityService.currentUser
//				if(p.isEditableByUser(secUser)){
//					List<String> auths =secUser.authorities*.authority
					UserRole uRole = UserRole.findByUser(secUser);
					if(uRole?.role?.authority?.contains("ROLE_ADMIN") || uRole?.role?.authority?.contains("ROLE_AMM")){
						AnomaliaBancaria ab = p.getAnomaliaBancaria()
						AnomaliaCounter ac = AnomaliaCounter.findByInterIDAndAnomalID(ab.getInterviewId(),ab.getAnomaliaBancariaType().id)
						ac.counter--
						ac.save(flush:true)
						p.delete(flush:true)
						
					}else{
						User amm = secUser.getParentRole("ROLE_AMM");
						if(amm && !amm.role?.authority?.contains("ROLE_AVV")){
							AnomaliaBancaria ab = p.getAnomaliaBancaria()
							p.user=amm
							p.save(flush:true)
						} else {
							message="{'message':'Non si possiedono i permessi per cancellare la Pratica selezionata!'}"
						}
					}
						message="{'message':'Pratica cancellata con successo!'}"
//				}else{
//						message="{'message':'Non si possiedono i permessi per cancellare la Pratica selezionata!'}"
//				}
				
			}else{
				message="{'message':'impossibile trovare Pratica e corrispettiva Anomalia Bancaria selezionata'}"
				
			}
			render JSON.parse(message) as JSON
		}

	
		
	def uploadInterviewFiles(){
		
		DocType dt = DocType.findByDocumentCategory(3);
		println params
		def interview = Interview.findById(params.intId)
		def folder = new File(grailsApplication.config.uploadFolder+File.separator+dt.documentType+File.separator+interview.id+File.separator)
				
		if( !folder.exists() ) {			
			folder.mkdirs()
		}
		
		def file = request.getFile('file')
		if(file.empty) {
			flash.message = "Il file non deve essere vuoto"
			//TODO redirect
		} else {
		def name_replace = file.originalFilename.replace(' ', '')
		def findName = FileDocument.findByFileNameAndDocumentType(name_replace,dt)
		if(!findName){
			
		def user = springSecurityService.currentUser
		def docInstance = new FileDocument()
		docInstance.user=user
				
				//replace del nome
//		def name_replace = file.originalFilename.replace(' ', '')
		docInstance.fileName = name_replace
			
		docInstance.comments = params.comments
		docInstance.filePath = folder
		docInstance.file_estension= file.contentType
		docInstance.fileSize=file.size
		docInstance.documentType = dt
		file.transferTo(new File(docInstance.filePath,name_replace))
		docInstance.save(flush:true)
		interview.fileDocument.add(docInstance)
		interview.save(flush:true)
		flash.message = message(code: 'File creato correttamente',)
				
		//TODO redirect
		
		 
		}				
	}	
	}
	
	def loadInterviewFolders(){
		
		Interview interview = Interview.findById(params.interviewId)
		
		def docTypeIntCodf = DocType.findByDocumentCategoryAndInterviewIdAndDocumentType(3,interview.id,'Codice Fiscale') ?:
		new DocType(
		documentType : 'Codice Fiscale',
		documentCategory:3,interviewId:interview.id
		).save(failOnError: true)
		
		def docTypeIntDocI = DocType.findByDocumentCategoryAndInterviewIdAndDocumentType(3,interview.id,'Documento Riconoscimento') ?:
		new DocType(
		documentType : 'Documento Riconoscimento',
		documentCategory:3,interviewId:interview.id
		).save(failOnError: true)
		
		def docTypeIntPrivacy = DocType.findByDocumentCategoryAndInterviewIdAndDocumentType(3,interview.id,'Privacy') ?:
		new DocType(
		documentType : 'Privacy',
		documentCategory:3,interviewId:interview.id
		).save(failOnError: true)
		
		def interviewFolders = DocType.findAllByDocumentCategoryAndInterviewId(3,interview.id)
		

		render template:'/_common/modals/foldersInterviewList', model:[folders:interviewFolders,interview:interview,interviewId:interview.id]
	}
	
	def interview_files_number(Interview interview){
		DocType folderType = DocType.findByIdAndDocumentCategory(params.folder_id,3)
		Interview interivewInstance = Interview.findById(params.iId)
		
		List<FileDocument> files = interview.fileDocument
		int result=0;
		if(files){
		files.each{FileDocument file->
			
			if(file.documentType.equals(folderType)){
				
				result++;
			}
		}
		}
		render result;
	}
	
	def filesInFolder(){
		
		DocType folderType = DocType.findByIdAndDocumentCategory(params.folderId,3)
		Interview interivewInstance = Interview.findById(params.iId)		
		List<FileDocument> files = interivewInstance.fileDocument
		List<FileDocument> fileInDir = new ArrayList<FileDocument>() 
		
		files.each{FileDocument file->			
			if(file.documentType.equals(folderType)){				
				fileInDir.push(file)
			}
		}		
		if(fileInDir){			
			if(params.order_by == 'name'){				
				render template:'/_common/modals/interviewListFiles', model:[files:fileInDir.sort{it.fileName.toLowerCase()},interv:interivewInstance]				
			}else{								
				render template:'/_common/modals/interviewListFiles', model:[files:fileInDir.sort{-it.dateCreated.time},interv:interivewInstance]			
			}			
		}else{					
			render template:'/_common/modals/interviewListFiles', model:[folderType:folderType]
		}		
	}	
	
	def uploadFromAj(){		
		DocType dt = DocType.findByIdAndDocumentCategory(params.folderId,3);
		def interview = Interview.findById(params.interviewId)
		def folder = new File(grailsApplication.config.uploadFolder+File.separator+'Interview'+File.separator+interview.id+File.separator+dt.documentType+File.separator)
				
		if( !folder.exists() ) {			
			folder.mkdirs()
		}				
		if(!(request.getFile('file'))) {
			response.status=401
			render  "Il file non deve essere vuoto"			
		} else {		
			def file = request.getFile('file')
			def name_replace = file.originalFilename.replace(' ', '')
//			def findName = FileDocument.findByFileNameAndDocumentType(name_replace,dt)
			List<FileDocument> listfileInterview = interview.fileDocument
			def findName = false
			listfileInterview.each {FileDocument ft->				
				if(ft.documentType== dt && ft.fileName.equals(name_replace)){					
					findName=true
				}				
			}						
			if(!findName){			
				def user = springSecurityService.currentUser
				def docInstance = new FileDocument()
				docInstance.user=user				
				docInstance.fileName = name_replace			
				docInstance.comments = params.comments
				docInstance.filePath = folder
				docInstance.file_estension= file.contentType
				docInstance.fileSize=file.size
				docInstance.documentType = dt
				file.transferTo(new File(docInstance.filePath,name_replace))
				docInstance.save(flush:true)
				interview.fileDocument.add(docInstance)
				interview.save(flush:true)
		
				response.status=200
				render "File caricato correttamente" 		 
			}else{			
				response.status=401
				render "Errore: Esiste un file con lo stesso nome"
			}				
		}		
	}
	
	
	def deleteIntervistaFile(){
		Interview intInstance= Interview.get(params.getLong('id_intervista'));
		List<FileDocument> fdList= intInstance.fileDocument
		def deleted = false
		fdList.any{FileDocument fd->			
			if(fd.id==params.getLong('id')){			
				intInstance.removeFromFileDocument(fd);
				intInstance.save(flush:true)
				File toDelete = new File(fd.filePath,fd.fileName)
				toDelete.delete()				
				deleted = true
			}			
		}		 
		if(deleted){			
			render "File cancellato correttamente"
		}else{
			//non riesco a cancellare il file
			response.status=401
			render "Non e' stato possibile cancellare il file"
		}				
	}
		
	
	def showInterviewFileDetail(){		
		def fileId = params.fileId
		FileDocument fd = FileDocument.findById(fileId)		
		if(fd){
			render template:'/_common/modals/intFileDetailPUp', model:[fd:fd]
		}else{
			
			response.status=401
			render "Impossibile recuperare le inforamazioni del file,riprovare piu tardi.."		
		}		
	}
	
		
	def downloadInterviewFile(){
		FileDocument fd=  FileDocument.findById(params.fileId)		
		if(fd){
			def filePath = fd.filePath+File.separator+fd.fileName
			//TODO settare content type on content type del file
			response.setContentType("APPLICATION/OCTET-STREAM")
			response.setHeader("Content-Disposition", "Attachment;Filename=\"${fd.fileName}\"")
			def file = new File(filePath)
			def fileInputStream = new FileInputStream(file)
			def outputStream = response.getOutputStream()
			byte[] buffer = new byte[4096];
			int len;
			while ((len = fileInputStream.read(buffer)) > 0) {
				outputStream.write(buffer, 0, len);
			}
			outputStream.flush()
			outputStream.close()
			fileInputStream.close()			
		}else{
			flash.message = message(code:"Non riesco a trovare il file")
//			TODO:redirect			
		}		
	}

		
	def addInterviewFolder(){		
		def type= params.documentType
		def interInstance = Interview.findById(params.interviewId)
		DocType findFolder = DocType.findByDocumentTypeAndDocumentCategoryAndInterviewId(type,3,params.interviewId)
		if(findFolder){			
			response.status = 401
			render message(code: 'Esite gia una cartella con questo nome')
		}else{
			DocType dt = new DocType(params)
			dt.documentCategory=3
			dt.interviewId=params.getInt('interviewId')
			if(dt.save(flush:true)){
				File folder = new File(grailsApplication.config.uploadFolder+File.separator+"Interview"+File.separator+params.interviewId+File.separator+dt.documentType+File.separator)
				if(folder.mkdirs()){
					def allFolders = DocType.findAllByDocumentCategoryAndInterviewId(3,params.getInt('interviewId'))
					render template:'/_common/modals/foldersInterviewList', model:[folders:allFolders,interview:interInstance,interviewId:interInstance.id]
				}else{
					response.status = 401
					render message(code: 'Non riesco a creare la cartella')
				}
			}
			else{
				response.status = 401
				render message(code: 'Devi specificare un nome per la cartella')				
			}
		}		
	}

		
	def deleteInterviewFolder(){		
		DocType erased = DocType.findById(params.folderId)
		Interview intInstance = Interview.findById(params.getInt('interviewId'))
		if(erased){			
			if(erased.documentType=="Codice Fiscale" || erased.documentType=="Documento Riconoscimento" || erased.documentType=="Privacy" ){				
				response.status=401
//				render "<div class='alert alert-danger fade in'><button class='close' data-dismiss='alert'>&#120;</button><i class='fa-fw fa fa-times'></i><strong>Cartella di sistema!</strong>Non &egrave possibile cancellare questa cartella</div>"
				render "Cartella di sistema!Non &egrave possibile cancellare questa cartella"
				}else{			
					File folderErased = new File(grailsApplication.config.uploadFolder+File.separator+"Interview"+ File.separator + erased.interviewId+File.separator  +erased.documentType)
					if(folderErased.exists()){
						//la cartella esiste cancella					
						if(deleteObjects(erased,intInstance)){
							folderErased.deleteDir()
							erased.delete(flush:true)
							
							def allFolders = DocType.findAllByDocumentCategoryAndInterviewId(3,intInstance.id)
							render template:'/_common/modals/foldersInterviewList', model:[folders:allFolders,interview:intInstance,interviewId:intInstance.id]							 
						}else{
							response.status=401
	//						render "<div class='alert alert-danger fade in'><button class='close' data-dismiss='alert'>&#120;</button><i class='fa-fw fa fa-times'></i><strong>Errore</strong>Non &egrave possibile cancellare questa cartella</div>"
							render "Errore:Impossibile trovare questa cartella!"
						}				
					}else{
	//					la cartella non esiste
						response.status=401
	//					render "<div class='alert alert-danger fade in'><button class='close' data-dismiss='alert'>&#120;</button><i class='fa-fw fa fa-times'></i><strong>Errore</strong>Non &egrave possibile cancellare questa cartella</div>"
						render "Errore!Non &egrave possibile cancellare questa cartella"
					}			
			}			
		}else{		
			response.status=401
			render "Errore!Impossibile trovare questa cartella"
		}		
	}

		
	private deleteObjects(DocType docTypeInst,Interview intervista){		
		def filedocs = FileDocument.findAllByDocumentType(docTypeInst)		
		boolean deleted = true
		filedocs.each {FileDocument fd->			
			intervista.removeFromFileDocument(fd);
				intervista.save(flush:true)			
		}		
		return true		
	}

		
	private String currencyFormatter(String currency){
		String result = currency.replaceAll('\\.','');
		result = result.replaceAll(',','.');
		return result;
	}
	
	
	def showUploadpopup(){		
		def interviewIns = Interview.findById(params.getInt('interviewId'))
		
		render template:'/_common/modals/fileInterviewUpload', model:[interviewId:interviewIns.id]		
	}

	
	def createInterviewPdf(){
		Interview interviewInstance = Interview.get(params.interId)
		Customer interCustomer = interviewInstance.customer
		Address domicilio = interCustomer.abode
		Address residenza = interCustomer.residence
//		PersonaGiuridica personaGiuridica = interCustomer.personaGiuridica
		Job jobInstance = interCustomer.job
		List<RenditaTitDep> listaRendite = new ArrayList<RenditaTitDep>()		
		def rendita = null
		
		PersonaGiuridica personaGiuridica = null
		Address residenzaGiuridica = null
		if(interCustomer.personaGiuridica){			
			personaGiuridica = interCustomer.personaGiuridica
			residenzaGiuridica=personaGiuridica.pgResidence
		}		
		JobType jobTypeInstance = null
		if(jobTypeInstance){
			jobTypeInstance = jobInstance.jobType
		}				
		def cpiInstance
		def cessioniDeleghe
		def cpi
		if(interviewInstance.acdCPI){			
			if(interviewInstance.acdCPI.cessioniDeleghe!=null){				
				if(interviewInstance.acdCPI.cessioniDeleghe==true){					
					cessioniDeleghe="SI"					
				}else{				
					cessioniDeleghe="NO"					
				}				
			}			
			if(interviewInstance.acdCPI.cPI!=null){				
				if(interviewInstance.acdCPI.cPI==true){
					cpi="SI"
				}else{
					cpi="NO"
				}				
			}			
		}else{			
			cessioniDeleghe=null
			cpi=null
		}		
		Map result = [:]
		result.data = []
		result.data << [
			interviewId:params.interviewId,
			customer:interCustomer,
			domicilio:domicilio,
			residenza:residenza,
			personaGiuridica:personaGiuridica,
			jobType:jobTypeInstance,
			listaRendite:interCustomer.renditaTitDep,
			note:interviewInstance.note,
			motiveInterview:interviewInstance.motiveInterview,
			cessioniDeleghe:cessioniDeleghe,
			cpi:cpi,
			famiglia:interCustomer.families,
			immobile:interCustomer.immobile,
			altroBene:interCustomer.altroBene,
			debito:interCustomer.debito,
			residenzaGiuridica:residenzaGiuridica
			]		
		params.SUBREPORT_DIR = servletContext.getRealPath('/reports') + "/"
		println servletContext.getRealPath('/reports') + "/"
		def rep = jasperService.buildReportDefinition(params,request.locale,result)
		ByteArrayOutputStream stream = jasperService.generateReport(rep)
		
		ByteArrayOutputStream stream2 = jasperService.generateReport(rep)
		Date d = new Date()
		String dateFormat= d.format("dd/MM/yyyy")
		String dateStampa = dateFormat.replace("/","")
		println dateStampa
		def nF = "intervista_"+interviewInstance.id+"_"+interCustomer.surname+"D"+dateStampa
		def nomeFile=nF.replace(' ', '')
		
		DocType docTypeInter = DocType.findByInterviewIdAndDocumentType(interviewInstance.id,"Dati Intervista")
		
		if(!docTypeInter){		
			docTypeInter = new DocType(				
				interviewId:interviewInstance.id,
				documentCategory:3,
				documentType:"Dati Intervista"		
				).save(flush:true)
		}
		
		def folder = new File(grailsApplication.config.uploadFolder+File.separator+'Interview'+File.separator+interviewInstance.id+File.separator+docTypeInter.documentType+File.separator)
		if( !folder.exists() ) {
			folder.mkdirs()
		}
		File f= new File(folder,nomeFile+".pdf")
		f << stream2.toByteArray()
		
		FileDocument fileInterview = new FileDocument()
		def user = springSecurityService.currentUser
		def docInstance = new FileDocument()
		docInstance.user=user		
		docInstance.fileName = nomeFile+".pdf"	
		docInstance.comments = ""
		docInstance.filePath = folder
		docInstance.file_estension= "pdf"
		docInstance.fileSize=f.size()
		docInstance.documentType = docTypeInter
		docInstance.save(flush:true)
		interviewInstance.fileDocument.add(docInstance)
		interviewInstance.save(flush:true)
				
		response.setHeader("Content-disposition", "attachment; filename=" + nomeFile + ".pdf")
		response.contentType = "application/pdf"
		response.outputStream << stream.toByteArray()		
	}		
}